#import "ThumbsViewController.h"
#import "ThumbsViewControllerDelegate.h"
#import "ThumbsView.h"

@implementation ThumbsViewController

@synthesize outerFrame;
@synthesize innerFrame;

- (id)initWithDelegate:(id<ThumbsViewControllerDelegate>)_delegate
{
    if (self = [super init])
    {
        delegate = [_delegate retain];
        outerFrame = CGRectMake(0, 0, 320, 480);
        innerFrame = CGRectMake(0, 20 + 44, 320, 480 - 20 - 44);
        
        self.wantsFullScreenLayout = YES;
    }
    return self;
}

- (void)loadView
{
    thumbsView = [[ThumbsView alloc] initWithFrame:outerFrame controller:self];
    self.view = thumbsView;
    [self reloadData];
}

- (void)viewDidUnload
{
    [thumbsView release];
    thumbsView = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    isVisible = YES;
    if (dataReloadPending)
        [self reloadData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    isVisible = NO;
}

- (void)dealloc
{
    [thumbsView release];
    [delegate release];
    [super dealloc];
}

- (void)reloadData
{
    if (isVisible == NO)
    {
        dataReloadPending = YES;
        return;
    }
    dataReloadPending = NO;    
    int n = [delegate thumbsViewControllerPhotosCount:self];
    [thumbsView setNumberOfPhotos:n];
    for (int i = 0; i < n; ++i)
        [delegate thumbsViewController:self fetchPhotoAtIndex:i];
}

- (void)fetchedPhoto:(UIImage *)photo atIndex:(int)index
{
    [thumbsView setPhoto:photo atIndex:index];
}

- (void)thumbTapped:(int)index
{
    [delegate thumbsViewController:self selectedPhotoAtIndex:index];
}

@end
